<template>
  <!--分析报表-案场客流查询 -->
  <el-row style="height:100%">
    <page report="true">
      <div class="page-content report-con">
        <reportheader
          :option="option"
          :isArea="true"
          :global="global"
        ></reportheader>
        <div class="hei13"></div>
        <div class='loadingClass'
            v-loading="xxloading"
            element-loading-text="请点击查询报表获取相关数据"
            element-loading-spinner="el-icon-caret-top"
            element-loading-background="rgba(245, 248, 254, 1)">
        <KPIEcharts
            :title="global.title" :y_danwei="y_danwei"
                        :x_data="xData" :y_data="yData" ref='echarts'
        ></KPIEcharts>
        <div class="hei13"></div>
        <KPITable  :tableData="table.tableData" :tableHead="table.tableHead"
                       ref='table' :title="global.title" :isShowExport="daochu" ></KPITable>

        </div>
      </div>
    </page>
  </el-row>
</template>
<style lang="scss">
  .loadingClass{
    .el-loading-mask{
      .el-loading-spinner{
        top: 80px;
        i{
          display: none;
        }
        .el-loading-text{
          font-size: 18px;
          font-weight: bold;
          color:#b4b6bd;
        }
      }
      
    }
  }
  .page-content {
    &.report-con {
      padding: 0 0;
    }
    padding: 15px;
    .fr {
      float: right;
    }
    .el-table {
      margin-bottom: 10px;
    }
    .paging {
      margin: 15px;
      height: 28px;
    }
    .hei13 {
      height: 15px;
      width: 100%;
    }
  }
</style>
<script>
  let moment = require("moment");
  import page from "@/components/page/page";
  import reportheader from "@/components/analyzeReport/reportpublic/reportKPIAreaHead";
  import KPIEcharts from "@/components/analyzeReport/reportpublic/KPIEcharts";
  import KPITable from "@/components/analyzeReport/reportpublic/KPITable";
  import reportGlobal from "@/components/global/reportGlobal";//公共配置
  let unit = reportGlobal.unit;
  let kpiName = reportGlobal.name;
  export default {
    data: function () {
      //表格数据
      var table = {
        tableData: [],
        tableHead: []
      }
      return {
        option: {
          shortcuts: 'dayShortcuts',
          caseTitle: "",
        },
        table: table,
        showType: 'time',  //展示类型(time:分时,distr:分布)
        DataV: {
          org_id_list:[],//区域id
          datetimeval:{},//时间
          KPI:'',//指标
          tag:'',//标签
          timeSizeCkeck:'',//时间粒度
        },      //head条件接收
        xData: [],
        yData: [],
        yName: [],
        y_danwei:'',
        titleText: "",
        commonData: null,
        timeSize: {
          list: [],
          check: ''
        },
        echartKpis: [],//echart指标
        global: {},//公共参数
        code: this.$route.query.code,        //通过菜单栏点击传过来的code判断使用的公共参数
        daochu:false,
        xxloading:true,   //提示信息遮罩层
      };
    },
    components: {
      page,
      reportheader,
      KPIEcharts,
      KPITable,
    },
    inject: ["reload"],
    created() {
      for (let i in reportGlobal.queryList) {
        if (this.code == reportGlobal.queryList[i].code) {
          this.global = reportGlobal.queryList[i]
        }
      }
      this.option.caseTitle = this.global.caseTitle
    },
    mounted() {
      //条件改变
      this.$Bus.$on("KPIAreaData", (org_id_list,datetimeval,KPI,tag,timeSizeCkeck)=>{
        if(this.xxloading)
        {
          this.xxloading=false;
        }
        this.DataV.org_id_list = org_id_list
        this.DataV.datetimeval = datetimeval
        this.DataV.KPI = KPI
        this.DataV.tag = tag
        this.DataV.timeSizeCkeck = timeSizeCkeck
        this.daochu = timeSizeCkeck.type == 'MIN' ? false : true
        this.Updata()
      });

      //切换企业时清空数据
      this.$Bus.$on('Remove', () => {
        this.removedata();
      });
    },
    beforeDestroy() {
      this.$Bus.$off('KPIAreaData');
      this.$Bus.$off('Remove');
    },
    watch: {
      commonData(val){
        if(val && Object.keys(val).length){
          this.Upecharts();
          this.Uptable();
        }
      },
      //当route变化的时候，主要是报表之前传参
      $route(val){
        this.reload()
      },
    },
    methods: {
      Updata() {
        let url = "/sys/report_new/time_division_sum?group_type=area&"+
          "tags=" + this.DataV.tag + "&indicator_keys=" + this.DataV.KPI + "&interval=" + this.DataV.timeSizeCkeck.tag +
          "&start_day=" + this.DataV.datetimeval.day[0] + "&end_day=" + this.DataV.datetimeval.day[1] + "&start_hm=" + this.DataV.datetimeval.hm[0] + "&end_hm=" + this.DataV.datetimeval.hm[1];
        let params = {
          org_id_list :this.DataV.org_id_list,
          org_type:3
        };
        this.$api.post(url,params)
        .then(data=>{
          if(data == '10001'){
            this.$message.error('无权操作该数据')
            return
          }
          if(data.data){
             console.log(data.data,'commonData');
            this.commonData = data.data
          }
        })
        .catch(err=>{
           console.log(err);
        })
      },

      getYname(Timearr){
        if(Timearr[0]==Timearr[1]){
          return Timearr[0];
        }
        else{
          return Timearr[0]+' ~ '+Timearr[1];
        }
      },

      //分时柱状图数据改变
      Upecharts() {
        if(!this.commonData.sum_list || !this.commonData.item_list){
          this.$message.error('没有数据！')
          this.$Bus.$emit('Loading', false);
          return
        }
        let sum_list = this.commonData.sum_list ? this.commonData.sum_list : []
        let item_list = this.commonData.item_list ? this.commonData.item_list : []
        let x_data = [];
        let y_data = {};
        x_data = sum_list.map(x=>x.time_tag)
        //拿到两个区域的名称作为key值
        for(let i in item_list){
          if(item_list[i].area_id == this.DataV.org_id_list[0]){
            y_data[item_list[i].area_name] = []
          }
          if(item_list[i].area_id == this.DataV.org_id_list[1]){
            y_data[item_list[i].area_name] = []
          }
        }

        for(let i in item_list){
          for(let j in x_data){
            if(x_data[j] == item_list[i].time_tag){
              y_data[item_list[i].area_name][j] = item_list[i][this.DataV.KPI]
            }
          }
        }
         console.log(x_data,'x_data');
         console.log(y_data,'y_data');
        this.xData = x_data
        this.yData = y_data
        this.$nextTick(() => {
          this.$refs.echarts.UpData(true);
          this.$Bus.$emit("Loading", false);
        })
      },

      myIsNaN(value) {
        return value !== value;
      },

      Uptable() {
        if(!this.commonData.sum_list || !this.commonData.item_list){
          this.$message.error('没有数据！')
          this.$Bus.$emit('Loading', false);
          return
        }
        let sum_list = this.commonData.sum_list
        let item_list = this.commonData.item_list
        let x_data = [];
        let t_data = [];
        let kpi = this.getkpiName(this.DataV.KPI)+'('+unit[this.DataV.KPI]+')';
        let bianhuaV={}; //变化值
        let bianhual={};//变化率
        x_data = sum_list.map(x=>x.time_tag)
        //先push出前两行数据
        for(let i in this.DataV.org_id_list){
          let obj = {
            area:'',
            kpi:'',
          }
          for(let j in x_data){
            obj[x_data[j]] = ''
          }
          for(let k in item_list){
            if(item_list[k].area_id == this.DataV.org_id_list[i]){
              obj.area = item_list[k].area_name
              obj.kpi = kpi
              obj[item_list[k].time_tag] = item_list[k][this.DataV.KPI] ? item_list[k][this.DataV.KPI] : null
            }
          }
          t_data.push(obj)
        }
        //再做变化值和变化率数据
        for(let i in t_data[0]){
          if(i == 'area'){
            bianhuaV[i] = '变化值'
            bianhual[i] = '变化率'
          }else if(i == 'kpi'){
            bianhuaV[i] = kpi
            bianhual[i] = kpi
          }else{
            bianhuaV[i] = t_data[0][i]&&t_data[1][i] ? Number(t_data[0][i]) - Number(t_data[1][i]) : '--'
            bianhual[i] = t_data[0][i]&&t_data[1][i]&&bianhuaV[i] != 0 ? ((t_data[0][i] / bianhuaV[i])*100).toFixed(2) + '%' : '--'
          }
        }
        t_data.push(bianhuaV)
        t_data.push(bianhual)
        for(let i in t_data){
          let arr = []
          for(let ii in t_data[i]){
            for(let j in x_data){
              if(x_data[j] == ii) arr.push(t_data[i][ii])
            }
          }
          if(i != 3){
            t_data[i].max = this.getMax(arr)
            t_data[i].min = this.getMin(arr)
            t_data[i].sum = this.getSum(arr)
            t_data[i].aver = t_data[i].sum == '--' ?'--' : this.getAver(arr,t_data[i].sum)
          }else{
            t_data[i].max = '--'
            t_data[i].min = '--'
            t_data[i].sum = '--'
            t_data[i].aver = '--'
          }
        }
        this.table.tableData = t_data;
        this.table.tableHead = x_data.map(x=>{
          return {label:x,prop:x}
        })
      },
      getMax(arr){
        arr = arr.filter(x=>{
          return x && x != '--'
        });
        if(arr.length){
          return arr.reduce(function(a , b){
            return b > a ? b : a;
          });
        }else{
          return '--'
        }
      },
      getMin(arr){
        arr = arr.filter(x=>{
          return x && x != '--'
        });
        if(arr.length){
          return arr.reduce(function(a , b){
            return b < a ? b : a;
          });
        }else{
          return '--'
        }
      },
      getSum(arr){
        arr = arr.filter(x=>{
          return x && x != '--'
        });
        if(arr.length){
          return arr.reduce((x,y)=>x+y)
        }else{
          return '--'
        }
      },
      getAver(arr,sum){
        return ((sum/arr.length).toFixed(2) *100)/100
      },

      //table提取指标对应的数据 //
      extractKpis(data, showKpislist) {
        let kpisval = [];
        for (let item in showKpislist) {
          let model = [];
          for (let i = 0; i < data.length; i++) {
            model.push(data[i][showKpislist[item]]);
          }
          kpisval.push(model);
        }

        return kpisval;
      },

      //得到指标中文名
      getkpiName(kpiname) {
        return kpiName[kpiname];
      },

      //清除数据
      removedata() {
        this.$refs.echarts.UpData(false);
        this.daochu=false;
        this.table.tableData = [];
        this.table.tableHead = [];
        this.commonData = null;
        this.DataV = {};
      },

    }
  };
</script>
